#include <windows.h>
#include <commctrl.h>
#include <tchar.h>
#include "log.h"
#include "ini.h"
#include "w_main.h"
#include "w_filter.h"
#include "w_detail.h"
#include "listview.h"
#include "resource.h"
#include "trayicon.h"
#include "tracelog.h"


//TCHAR ccc[1000]={_T("x")};
HWND	hwndListView;
bool	isWndTopmost = false;
long	delayLog = 0;
//BOOL	dataReceived=false;
//TCHAR ccc2[1000]={_T("x")};


long CALLBACK w_main_proc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);

HWND createMainWindow(HINSTANCE hInst,_TCHAR * title) {
	if(!title)title=_T("Trace Log");
	
	_TCHAR	*classname = _T("TRACELOG_MAIN_WINDOW");
	WNDCLASS	wc;
	HWND		hwnd;
	
	memset(&wc, 0x00, sizeof(WNDCLASS));
	
	wc.style           = 0;
	wc.lpfnWndProc	   = (WNDPROC)w_main_proc;
	wc.cbClsExtra      = 0;
	wc.cbWndExtra      = 0;
	wc.hIcon           = LoadIcon(hInst, MAKEINTRESOURCE(ICON_LOG));
	wc.hCursor		   = LoadCursor (NULL, IDC_ARROW) ;
	wc.hInstance 	   = hInst;
	wc.hbrBackground   = (HBRUSH)GetStockObject(WHITE_BRUSH);
	wc.lpszClassName   = classname;
	if (!RegisterClass(&wc)) {
		if (!UnregisterClass(classname, hInst ) ) {
			log(_T("ERROR: createMainWindow:UnregisterClass failed.\n"));
			return NULL;
		}
		if (!RegisterClass(&wc)) {
			log(_T("ERROR: createMainWindow:RegisterClass failed.\n"));
			return NULL;
		}
	}
	   
	hwnd = CreateWindowEx( WS_EX_TOOLWINDOW, classname, title,
		WS_DLGFRAME|WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_CLIPCHILDREN | DS_MODALFRAME ,
		0, 35,680,230, NULL, NULL, hInst, NULL	
	);
	CloseWindow(hwnd);//minimize it and hide	
	if ( !hwnd ) {
		log(_T("ERROR: createMainWindow:CreateWindow failed.\n"));
		return NULL;
	}
	return hwnd;
}

long CALLBACK w_main_proc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
	switch (message) {
		case WM_SYSCOMMAND:
			switch (wParam) {
				case SC_CLOSE:
					ShowWindow(hWnd, SW_MINIMIZE);
					return 0;
			}
			break;
		case WM_CLOSE:
			ini_savewinpos(_T("tracelog.w_main"),hWnd);
			saveColWidth(hwndListView);
			deleteTrayIcon(hWnd);
			SendMessage(getDetailHWND(),WM_CLOSE,0,0);
			PostQuitMessage(0);
			return 0;
		case WM_CREATE:
			hwndListView=createListView(hWnd);
			if ( !hwndListView ){
				SendMessage(hWnd, WM_CLOSE, 0, 0);
				return 0;
			}
			ini_loadwinpos(_T("tracelog.w_main"),hWnd);
			createTrayIcon(hWnd);
			break;
		case WM_DESTROY:
			break;
		case WM_SIZE:
			if (wParam==SIZE_MINIMIZED) {
				if ( IsWindowVisible(hWnd) ) ShowWindow (hWnd, SW_HIDE);
			} else {
				MoveWindow(hwndListView, 0, 0, LOWORD(lParam), HIWORD(lParam), true);
				break;
			}
			break;
		case WM_ACTIVATE:
			if(LOWORD(wParam)!=WA_INACTIVE){
				PostMessage(hWnd,MYWM_SETFOCUS,0,0);
			}
			break;
		case MYWM_SETFOCUS:
			SetFocus(hwndListView);
			break;
		case MYWM_REFRESHDATA:
			//add item to the log
			if (tracelog_read(hwndListView)>=0 )PostMessage(hWnd,MYWM_REFRESHDATA,0,0);
			return 0;
		case TIM_NOTIFY:
			switch (lParam) {
				case WM_RBUTTONDOWN:
					POINT pt;
					GetCursorPos(&pt);
					PostMessage(hwndListView, WM_CONTEXTMENU, wParam, MAKELPARAM(pt.x, pt.y));
					break;
				case WM_LBUTTONDOWN:
					alertTrayIcon(hWnd, false); //remove alert status from tray icon
					if ( IsWindowVisible(hWnd) ) {
						CloseWindow (hWnd); //minimize, so hide
					} else {
						ShowWindow (hWnd, SW_RESTORE);
						PostMessage(hWnd, MYWM_SETFOREGROUND,0,0);
					}
					break;
			}
			return 0;
		case WM_NOTIFY:
			NM_LISTVIEW * pnmlv;
			pnmlv=(NM_LISTVIEW*) lParam;
			if(pnmlv->hdr.hwndFrom==hwndListView){
				if(pnmlv->hdr.code==LVN_ITEMCHANGED){
					if (pnmlv->uNewState&LVIS_FOCUSED){
						setListViewDetail(hwndListView,pnmlv->iItem);
					}
				}
			}
			return 0;
		case MYWM_SETFOREGROUND:
			SetForegroundWindow(hWnd);
			return 0;
		case WM_COMMAND:
			if ( HIWORD(wParam) == 0 ) {
				switch( LOWORD(wParam) ) {
					case ID_LOG_FILTER:
						createFilterDialog(hWnd);
						break;
					case ID_LOG_CLEAR:
						clearWindowLog();
						break;
					case ID_LOG_REFRESH:
						clearWindowLog();
						tracelog_rewind();
						PostMessage(hWnd,MYWM_REFRESHDATA,0,0);
						break;
					case ID_LOG_SAVEAS:
						saveListViewAs(hwndListView);
						break;
					case ID_LOG_ALWAYSONTOP:
						//switch "always on top"
						SetWindowPos( hWnd, isWndTopmost ? HWND_NOTOPMOST : HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); 
						isWndTopmost = !isWndTopmost;
						break;
					case ID_LOG_DELAY:
						if(delayLog)delayLog=0;
						else delayLog=1000;
						break;
					case ID_LOG_ABOUT:{
						WCHAR c[100];
						WCHAR *t=L"TraceLog\ncreated by Dmitry Lukyanov (http://LDU.da.ru)\n\nMenu Commands:\n"
						L"\tClear\t\tClear all log items (they still remain in the memory)\n"
						L"\tRefresh\t\tRefresh the whole log (restore the log after clearing)\n"
						L"\tAlways on top\tSet the log window to be topmost\n"
						L"\tDelay\t\tEach insert into the log will take 1 sec, so you will see it slowly\n"
						L"\tFilter...\t\tSpecify the types of log items you want to see\n";
						L"\nBuilt on 2006-02-26 (YMD)";
						GetWindowText(hWnd,c,NUMTCHARS(c) );
						MessageBox(hWnd,t,c,MB_OK|MB_ICONINFORMATION);
						break;
					}
					case IDOK:
						showDetailWindow();
//						long curItem;
//						curItem=ListView_GetNextItem(hwndListView,-1,LVNI_FOCUSED);
//						if(curItem>=0)popupMemoWnd(curItem);
						break;
					case IDCANCEL:
						CloseWindow(hWnd);
						break;
				}
			}
			return 0;
	}
	return DefWindowProc(hWnd, message, wParam, lParam); 
}


void clearWindowLog(){
	ListView_DeleteAllItems(hwndListView);
}

